﻿Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Runtime.InteropServices

Namespace System.Workflow.Runtime
    <DefaultMember("Item")> _
    Friend Class FanOutOnKeyDictionary([Of] K, V)
        Implements IEnumerable([Of] Dictionary([Of] K, V)), IEnumerable
        ' Methods
        Public Sub New(ByVal fanDegree As Integer)
            Me.dictionaryDictionary = New Dictionary([Of] Integer, Dictionary([Of] K, V))(fanDegree)
            Dim i As Integer
            For i = 0 To fanDegree - 1
                Me.dictionaryDictionary.Add(i, New Dictionary([Of] K, V))
            Next i
        End Sub

        Public Function GetEnumerator() As IEnumerator([Of] Dictionary([Of] K, V))
            Return Me.dictionaryDictionary.Values.GetEnumerator
        End Function

        Public Function SafeTryGetValue(ByVal key As K, <Out> ByRef value As V) As Boolean
            Dim dictionary As Dictionary([Of] K, V) = Me.Item(key)
            SyncLock dictionary
                Return dictionary.TryGetValue(key, value)
            End SyncLock
        End Function

        Private Function System.Collections.IEnumerable.GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
            Return Me.dictionaryDictionary.Values.GetEnumerator
        End Function


        ' Properties
        Public ReadOnly Default Property Item(ByVal key As K) As Dictionary([Of] K, V)
            Get
                Return Me.dictionaryDictionary.Item(Math.Abs(CInt((key.GetHashCode Mod Me.dictionaryDictionary.Count))))
            End Get
        End Property


        ' Fields
        Private dictionaryDictionary As Dictionary([Of] Integer, Dictionary([Of] K, V))
    End Class
End Namespace

